import { useState, useEffect } from 'react';

import store from '../redux/store';

import { getCityList } from '../redux/action/CityActionCreator';

const useCity = () => {
  const [cityId, setCityId] = useState(store.getState().CityReducer.city.id);
  const [cityName, setCityName] = useState(
    store.getState().CityReducer.city.name
  );

  useEffect(() => {
    // 订阅
    let unsubscribe = store.subscribe(() => {
      let { id, name } = store.getState().CityReducer.city;
      setCityId(id);
      setCityName(name);
    });
    return () => {
      // 取消订阅
      unsubscribe();
    };
  }, []);

  return { cityId, cityName };
};

const useCityList = () => {
  const [list, setList] = useState([]);

  useEffect(() => {
    if (store.getState().CityReducer.cityList.length === 0) {
      store.dispatch(getCityList());
    } else {
      console.log('useCity 缓存');
    }
    return () => {};
  }, []);

  useEffect(() => {
    // 订阅
    let unsubscribe = store.subscribe(() => {
      setList(store.getState().CityReducer.cityList);
    });
    return () => {
      // 取消订阅
      unsubscribe();
    };
  }, []);
  return {
    list,
  };
};

export { useCity, useCityList };
